<template>
  <div>
    <el-form :model="searchFormData" label-width="60px">
      <el-row :gutter="15" style="flex-wrap: wrap; flex-direction: row">
        <el-col :span="6">
          <el-form-item label="昵称" prop="nickName">
            <el-input
              placeholder="请输入昵称"
              v-model="searchFormData.nickNameFuzzy"
              clearable
              @keyup.enter="loadDataList"
              ><template #prefix
                ><span class="iconfont icon-account"></span></template
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号" prop="phone">
            <el-input
              placeholder="请输入手机号"
              v-model="searchFormData.phoneFuzzy"
              clearable
              @keyup.enter="loadDataList"
              ><template #prefix
                ><span class="iconfont icon-phone"></span></template
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button plain color="#409eff" @click="loadDataList"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="1">
          <el-button plain color="#7fc65a" @click="showEdit('add')"
            >新增成员</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <Table
      :columns="columns"
      :showPagination="false"
      :dataSource="tableData"
      :fetch="loadDataList"
      :options="tableOptinos"
    >
      <!-- 头像 -->
      <template #avatar="{ row }">
        <Cover :cover="row.avatar"></Cover>
      </template>
      <!-- 用户信息 -->
      <template #userInfo="{ row }">
        <div>昵称：{{ row.nickName }}</div>
        <div>手机号：{{ row.phone }}</div>
        <div>学校：{{ row.profession }}</div>
      </template>
      <!-- 类型 -->
      <template #typeName="{ row }">
        <div>
          {{ row.roleTypeName }}
        </div>
        <div v-if="row.type == 1">转载地址：{{ row.reprintUrl }}</div>
      </template>
      <!-- 状态 -->
      <template #statusInfo="{ row }">
        <span v-if="row.status == 1" style="color: green">{{
          row.statusName
        }}</span>
        <span v-else style="color: red">{{ row.statusName }}</span>
      </template>
      <!-- 时间 -->
      <template #timeInfo="{ row }">
        <div>创建时间：{{ row.createTime }}</div>
        <div>最后登录：{{ row.lastLoginTime }}</div>
      </template>

      <template #operation="{ row }">
        <span v-if="userInfo.roleType == 1">
          <a
            href="javascript:void(0)"
            @click="showEdit('edit', row)"
            class="a-link"
            >修改</a
          >
          <el-divider direction="vertical" />
          <a
            href="javascript:void(0)"
            class="a-link"
            @click="changeAccountStatus(row)"
            >{{ row.status == 0 ? "启用" : "禁用" }}</a
          >
          <el-divider direction="vertical" />
          <a
            href="javascript:void(0)"
            @click="showUpdataPassword(row.userId)"
            class="a-link"
            >修改密码</a
          >
          <el-divider direction="vertical" />
          <a
            href="javascript:void(0)"
            @click="delUser(row)"
            class="a-link"
            style="color: red"
            >删除</a
          >
        </span>
        <span v-else> --- </span>
      </template>
    </Table>
    <!-- 新增成员弹窗 -->
    <Dialog
      :show="editDialogInfo.show"
      :title="editDialogInfo.title"
      :buttons="editDialogInfo.buttons"
      width="50%"
      @close="editDialogInfo.show = false"
    >
      <el-form
        ref="editFormRef"
        :model="formData"
        :rules="rules"
        label-width="95px"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input
                placeholder="起一个好听的名字"
                v-model="formData.nickName"
                :maxlength="30"
                ><template #prefix
                  ><span class="iconfont icon-account"></span></template
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input
                placeholder="这里填写手机号"
                v-model="formData.phone"
                :maxlength="11"
                ><template #prefix
                  ><span class="iconfont icon-phone"></span></template
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                type="password"
                placeholder="至少8位，需要包含数字、字母和特殊字符"
                v-model="formData.password"
                ><template #prefix
                  ><span class="iconfont icon-password"></span></template
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重复密码" prop="rePassword">
              <el-input
                type="password"
                placeholder="请再次输入密码"
                v-model="formData.rePassword"
                ><template #prefix
                  ><span class="iconfont icon-password"></span></template
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="默认编辑器" prop="editorType">
              <el-radio-group v-model="formData.editorType">
                <!-- <el-radio label="富文本编辑器" :value="0"></el-radio>
              <el-radio label="Markdown编辑器" :value="1"></el-radio> -->
                <el-radio :label="0">富文本编辑器</el-radio>
                <el-radio :label="1">Markdown编辑器</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学校" prop="profession">
              <el-input placeholder="请输入学校" v-model="formData.profession"
                ><template #prefix
                  ><span class="iconfont icon-school-copy"></span></template
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="头像" prop="avatar">
              <CoverUpload
                v-model="formData.avatar"
                @callback="saveAvatar"
              ></CoverUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-row :span="24">
            <el-form-item label="简介" prop="introduction">
                <EditorHtml
                style="height: 25vh; overflow: hidden;"
                  id="introduction"
                  v-model="formData.introduction"
                  ref="introduction"
                ></EditorHtml>
              
            </el-form-item>
          </el-row>
        </el-row>
      </el-form>
    </Dialog>
    <!-- 修改密码弹窗 -->
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      @close="dialogConfig.show = false"
    >
      <el-form
        ref="passwordFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            placeholder="至少8位，需要包含数字、字母和特殊字符"
            v-model="formData.password"
            size="large"
            ><template #prefix
              ><span class="iconfont icon-password"></span></template
          ></el-input>
        </el-form-item>
        <el-form-item label="重复密码" prop="rePassword">
          <el-input
            type="password"
            placeholder="请再次输入密码"
            v-model="formData.rePassword"
            size="large"
            ><template #prefix
              ><span class="iconfont icon-password"></span></template
          ></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, reactive, ref } from "vue";
import VueCookies from "vue-cookies";

const { proxy } = getCurrentInstance();

const userInfo = ref(VueCookies.get("userInfo") || {});

const api = {
  loadDataList: "/setting/loadUser",
  saveTeamUser: "/setting/saveTeamUser",
  updateStatus: "/setting/updateStatus",
  delUser: "/setting/delUser",
  updatePassword : "/setting/updatePassword"
};

const searchFormData = ref({});

const loadDataList = async () => {
  let params = {
    pageNo: tableData.value.pageNo,
    pageSize: tableData.value.pageSize,
  };
  Object.assign(params, searchFormData.value);

  let result = await proxy.Request({
    url: api.loadDataList,
    params: params,
  });
  if (!result) {
    return;
  }
  tableData.value = result.data; //ref()的用法
  // Object.assign(tableData,result.data); //reactive()的用法
};

//列表
const columns = [
  {
    label: "头像",
    prop: "avatar",
    width: 100,
    scopedSlots: "avatar",
  },
  {
    label: "用户信息",
    prop: "nickName",
    scopedSlots: "userInfo",
  },
  {
    label: "默认编辑器",
    prop: "editorTypeName",
    width: 100,
  },
  {
    label: "类型",
    prop: "typeName",
    scopedSlots: "typeName",
  },
  {
    label: "角色",
    prop: "roleTypeName",
    scopedSlots: "roleInfo",
    width: 75,
  },
  {
    label: "状态",
    prop: "statusInfo",
    width: 75,
    scopedSlots: "statusInfo",
  },
  {
    label: "时间",
    prop: "createTime",
    width: 250,
    scopedSlots: "timeInfo",
  },
  {
    label: "操作",
    prop: "operation",
    width: 150,
    scopedSlots: "operation",
  },
];

const tableData = ref({});

const tableOptinos = {
  extHeight: 50,
  stripe: true,
};


// 新增用户
const validateRePass = (rule, value, callback) => {
  if (value !== formData.value.password) {
    callback(new Error(rule.message));
  } else {
    callback();
  }
};
const rules = {
  nickName: [{ required: true, message: "昵称不能为空" }],
  editorType: [{ required: true, message: "请选择默认编辑器" }],
  password: [
    { required: true, message: "请输入密码" },
    {
      validator: proxy.Verify.password,
      massge: "密码最少八位，且仅有数字字母与特殊字符",
    },
  ],
  rePassword: [
    { required: true, message: "请再次输入密码" },
    { validator: validateRePass, message: "两次输入的密码不一致" },
  ],
  phone: [
    { required: true, message: "请输入手机号" },
    {
      validator: proxy.Verify.phone,
      trigger: "blur",
      message: "请输入正确的手机号",
    },
  ],
};

const editDialogInfo = reactive({
  show: false,
  title: "新增用户",

  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

const formData = ref({});
const editFormRef = ref();
const showEdit = (type, data) => {
  editDialogInfo.show = true;
  nextTick(async () => {
    editFormRef.value.resetFields();
    if (type === "add") {
      editDialogInfo.edit = false;
      editDialogInfo.title = "新增账号";
      formData.value = { introduction: "" };
    } else {
      editDialogInfo.edit = true;
      editDialogInfo.title = "修改账号";
      Object.assign(formData.value,data);
    }
  });
};

const submitForm = () => {
  editFormRef.value.validate(async (valid) => {
    if (!valid) {
      return false;
    }
    let params = {};
    Object.assign(params, formData.value);
    delete params.createTime;
    delete params.lastLoginTime;
    let result = await proxy.Request({
      url: api.saveTeamUser,
      params: params,
    });
    if (!result) {
      return;
    }
    editDialogInfo.show = false;
    proxy.Message.success("保存成功");
    loadDataList();
  });
};

//修改状态
const changeAccountStatus = (data) => {
  let status = data.status == 0 ? 1 : 0;
  let statusName = data.status == 0 ? "启用" : "禁用";
  proxy.Confirm(`你确定要 ${statusName} <b>${data.nickName}</b> 吗?`, async () => {
    let result = await proxy.Request({
      url: api.updateStatus,
      params: {
userId: data.userId,status: status      },
    });
    if (!result) {
      return;
    }
    loadDataList();
  });
};

//删除
const delUser = (data) => {
  proxy.Confirm(`你确定要删除 <b>${data.categoryName}</b> 吗?`, async () => {
    let result = await proxy.Request({
      url: api.delUser,
      params: {
        categoryId: data.userId,
      },
    });
    if (!result) {
      return;
    }
    loadDataList();
  });
};

// 修改密码
const passwordFormRef = ref(null);
const dialogConfig = reactive({
  show: false,
  title: "修改密码",

  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitPass();
      },
    },
  ],
});

const showUpdataPassword = (useId) => {
  dialogConfig.show = true;
  nextTick(() => {
    // formDataRef.value.resetFields();
    formData.value = {userId: useId};
  });
};

const submitPass = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let result = await proxy.Request({
      url: api.updatePassword,
      params: {
        userId: formData.value.userId,
        password: formData.value.password,
      },
    });
    if (!result) {
      return;
    }
    dialogConfig.show = false;
    proxy.Message.success("修改密码成功");
  });
};
</script>

<style scoped lang="scss">
</style>